<template>
  <div class="app-container">

    <div class="">
      <!-- <div style="margin-bottom: 20px;">
        <el-alert type="error">
            蓝色加粗的是菜单
        </el-alert>

        <el-button type="primary" @click="append(1,authdata)" size="mini">
            增加权限
        </el-button>

        <el-button type="success" @click="authsortsave" size="mini">
            排序保存
        </el-button>
      </div> -->
    <!-- <el-tree
    ref="tree"
    :data="authdata"
    node-key="id"
    :props="defaultProps"
    :default-expand-all="false"
    :expand-on-click-node="false"
    :render-content="renderContent"
    draggable
    :allow-drop="allowDrop"
    @node-drag-end="handleDragEnd"
    >
    </el-tree> -->

    <div style="margin: 20px; font-weight: 700;">
        <el-button type="primary" @click="tableAddHandler" size="mini">
            增加权限
        </el-button>
    </div>

    <el-table :header-cell-style="{background:'#e5eeff',height:'60px',color:'#777'}" :data="authdata" :style="{ width: '100%' }" row-key="id" :tree-props="{children: 'sons', hasChildren: 'hasChildren'}">
          <el-table-column
            prop="title"
            label="权限名称"
            width="280" header-align="center">
            <template v-slot="scope">
              <span  style="margin-left: 20px;">{{scope.row.title}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="icon" label="icon图标" width="180"  align="center">
            <template v-slot="scope">
              <i v-if="scope.row.icon" :class="[scope.row.icon]"></i>
              <i v-else :class="['iconfont',scope.row.icon]">-</i>
            </template>
          </el-table-column>
          <el-table-column  label="是否是菜单" width="180" >
            <template v-slot="scope">
                <span v-if="scope.row.is_menu==1"> <el-tag type="success"  >是菜单</el-tag>
                  </span>
                <span v-else><el-tag type="waring"  >不是菜单</el-tag> </span>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" width="180" />
          <el-table-column prop="name" label="权限路由" width="180" />
          <el-table-column prop="path" label="路由地址" width="180" />
          <el-table-column prop="remark" label="备注" >
            <template v-slot="scope">
              <p>{{scope.row.remark || '-'}}</p>
            </template>
          </el-table-column>
          <el-table-column  label="操作" min-width="200" align="center">
            <template v-slot="scope">
              <el-button type="success" size="mini" @click="tableAddHandler(scope.row)">添加子级</el-button>
                <el-button type="primary" size="mini" @click="tableEditHandler(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" @click="tableDelHandler(scope.row)">删除</el-button>
            </template>
          </el-table-column>
      </el-table>

    </div>

    <el-dialog title="保存权限" :visible.sync="createFormBox">
      <el-form ref="form" :model="data" label-width="120px" :rules="rules" style="margin-top: 20px;">
            <el-form-item label="权限名称" prop="title">
                <el-input v-model="data.title"></el-input>
            </el-form-item>

            <el-form-item label="权限路由" prop="name">
                <el-input v-model="data.name" placeholder="如 Shop/shopList"></el-input>
            </el-form-item>

            <el-form-item label="菜单" prop="is_menu">
                <el-radio-group v-model="data.is_menu">
                <el-radio :label="1">菜单</el-radio>
                <el-radio :label="2">不是菜单</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="图标" prop="icon">
                <el-input v-model="data.icon"></el-input>
            </el-form-item>

            <el-form-item label="路径" prop="path">
                <el-input v-model="data.path" placeholder="一级如/shop二级如shop-list"></el-input>
            </el-form-item>

            <el-form-item label="页面路径" prop="component">
                <el-input v-model="data.component" placeholder="如/shop/shop-list"></el-input>
            </el-form-item>

            <el-form-item label="排序" prop="sort">
                <el-input v-model="data.sort"></el-input>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
                <el-input v-model="data.remark"></el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="rulesave()">
                保存
                </el-button>
            </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">

      </div>
    </el-dialog>


    <el-dialog title="添加权限" :visible.sync="createFormBox2">
      <el-form ref="form2" :model="data2" label-width="120px" :rules="rules" style="margin-top: 20px;">
             <el-form-item v-if="data2.parentTitle" label="父级权限" >
                <el-input v-model="data2.parentTitle" disabled></el-input>
            </el-form-item>
            <el-form-item label="权限名称" prop="title">
                <el-input v-model="data2.title"></el-input>
            </el-form-item>

            <el-form-item label="权限路由" prop="name">
                <el-input v-model="data2.name" placeholder="如 Shop/shopList"></el-input>
            </el-form-item>

            <el-form-item label="菜单" prop="is_menu">
                <el-radio-group v-model="data2.is_menu">
                <el-radio :label="1">菜单</el-radio>
                <el-radio :label="2">不是菜单</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="图标" prop="icon">
                <el-input v-model="data2.icon"></el-input>
            </el-form-item>

            <el-form-item label="路径" prop="path">
                <el-input v-model="data2.path" placeholder="一级如/shop二级如shop-list"></el-input>
            </el-form-item>

            <el-form-item label="页面路径" prop="component">
                <el-input v-model="data2.component" placeholder="如/shop/shop-list"></el-input>
            </el-form-item>

            <el-form-item label="排序" prop="sort">
                <el-input v-model="data2.sort"></el-input>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
                <el-input v-model="data2.remark"></el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="rulesave2()">
                保存
                </el-button>
            </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">

      </div>
    </el-dialog>

  </div>
</template>
<style>
.is_menu{color: rgb(64, 158, 255);font-weight: bold;}
.create-form-title {font-size: 16px;font-weight: bold;margin: 20px 0;}
.create-form-des {font-size: 13px;color: #aaa;}
</style>
<script>
import {authlist,authsave,authadd,authedit,authdel,authsortsave,authaddnew} from '@/api/auth'
import { MessageBox, Message } from 'element-ui'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
let id = 1000;
export default {
  name: 'auth-list',
  components: { },
  directives: { waves },
  filters: {
  },
  data() {
    return {
      fullscreenLoading: false,
      strictly: true,//父子不互相关联 true 是不关联
      defaultProps: {
        children: 'sons',
        label: 'title',
        id: 'id'
      },
      authdata:[],
      checked_auth_ids: [],
      /*authdata: [{
        label: '一级 1',
        children: [{
          label: '二级 1-1',
          children: [{
            label: '三级 1-1-1'
          }]
        }]
      }],*/
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        keyword: "",//搜索
        sort: 'id_desc'//默认的排序
      },
      data: {
        id: 0,
        title:"",
        remark: "",
        auth_ids: [],
        component:''
      },
      data2:{
        id: 0,
        title:"",
        remark: "",
        auth_ids: [],
        parentTitle:'',
        parentId:0,
        is_menu:1,
        component:''
      },
      createFormBox: false,//创建表单盒子显示和隐藏
      createFormBox2:false,//
      rules: {
        title: [{ required: true, message: '权限名称不能为空', trigger: 'change' }],
        name: [{ required: true, message: '权限路由不能为空', trigger: 'change' }],
        path: [{ required: true, message: '路径不能为空', trigger: 'change' }],
      },
    }
  },
  created() {
    this.getAuth()
  },
  methods: {
    //添加子权限或者新增
    tableAddHandler(data){
      if(data.title){
        this.data2.parentTitle=data.title;
        this.data2.parentId=data.id
      }else{
        this.data2.parentTitle='';
        this.data2.parentId=0
      }
      this.createFormBox2 = true;
    },
    //权限删除
    tableDelHandler(data){
      this.$confirm('确定删除此权限吗？其下所有子权限也会被删除！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          authdel({id:data.id}).then(response => {
              var code = response.code;
              var msg = response.msg;
              if (code == 200) {
                this.$message.success('删除成功');
                this.getAuth2()
              } else {
                this.$message({
                  message: msg,
                  type: 'error'
                });
              }
          })
        })
    },
    //表格编辑
    tableEditHandler(data){
      this.data = data;
      this.createFormBox = true;
    },
    //增加子权限
    append(node, data) {
        var level = node.level;
        var pid = data.id;
        authadd({pid:pid,level: level}).then(response => {
              var code = response.code;
              var msg = response.msg;
              if (code == 200) {
                    if (node == 1) {
                        this.authdata = [];
                        this.getAuth();
                    } else {
                        var auth_id = response.response.id;
                        var title = response.response.title;
                        const newChild = { id: auth_id, title: title, sons: [] };
                        if (!data.sons) {
                        this.$set(data, 'sons', []);
                        }
                        data.sons.push(newChild);
                    }
              } else {
                this.$message({
                  message: msg,
                  type: 'error'
                });
              }
        })
      },
      //编辑当前的权限
      edit(data) {
        this.data = data;
        this.createFormBox = true;
      },
      //删除当前的权限
      remove(node, data) {
        this.$confirm('确定删除此权限吗？其下所有子权限也会被删除！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          authdel({id:data.id}).then(response => {
              var code = response.code;
              var msg = response.msg;
              if (code == 200) {
                  const parent = node.parent;
                  const sons = parent.data.sons || parent.data;
                  const index = sons.findIndex(d => d.id === data.id);
                  sons.splice(index, 1);
              } else {
                this.$message({
                  message: msg,
                  type: 'error'
                });
              }
          })
        });
      },
      renderContent(h, { node, data, store }) {
        let level = node.level;
        if (level <= 2) {
            var add = <el-button size="mini" type="text" on-click={ () => this.append(node, data) }>增加子项</el-button>;
        } else {
            var add = '';
        }

        let is_menu = data.is_menu;
        if (is_menu == 1) {
            var menu = <span class='is_menu'>{node.label}</span>;
        } else {
            var menu = <span>{node.label}</span>;
        }

        return (
          <span class="custom-tree-node">
            {menu}
            <span>
              {add}
              <el-button size="mini" type="text" on-click={ () => this.edit(data) }>编辑</el-button>
              <el-button size="mini" type="text" on-click={ () => this.remove(node, data) }>删除</el-button>
            </span>
          </span>);
    },
    handleNodeClick(data) {
       //console.log(data);
    },
    //拖拽结束触发的方法
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
        //console.log('tree drag end: ', dropNode && dropNode.label, dropType);
        //alert("ddd");
        //console.log(this.authdata);
    },
    authsortsave(){
         //权限排序
         const loading = this.$loading({
          lock: true,
          text: '排序保存中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        authsortsave({data:this.authdata}).then(response => {
              loading.close();
              var code = response.code;
              var msg = response.msg;
              if (code == 200) {
                this.$message({
                  message: msg,
                  type: 'success'
                });
              } else {
                this.$message({
                  message: msg,
                  type: 'error'
                });
              }
          })
    },
    // 拖拽时判定目标节点能否被放置
    // 'prev'、'inner' 和 'next'，前、插入、后
    allowDrop(draggingNode, dropNode, type) {
      if (draggingNode.data.level === dropNode.data.level) {
        if (draggingNode.data.parentId === dropNode.data.parentId) {
          return type === "prev" || type === "next";
        } else {
          return false;
        }
      } else {
        //不同级进行处理
        return false;
      }
    },
    //获得所有的权限
    getAuth(){
        const loading = this.$loading({
          lock: true,
          text: '加载中……',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        authlist({type: 1}).then(response => {
            setTimeout(() => {
             loading.close();
            }, 100)

            if (response.code == 200) {
              var authdata = this.authdata;
              var auth = response.response;
              auth.forEach(item => {
                const menu = {
                  title: item.title,
                  name: item.name,
                  sons: item.sons,
                  id: item.id,
                  is_menu: item.is_menu,
                  pid: item.pid,
                  path: item.path,
                  sort: item.sort,
                  icon: item.icon,
                  component:item.component,
                  remark:item.remark
                }
                authdata.push(menu)
              })
            }
        }).catch(err => {
          setTimeout(() => {
             loading.close();
          }, 100)
        })
    },

     //获得所有的权限
     getAuth2(){
        const loading = this.$loading({
          lock: true,
          text: '加载中……',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        authlist({type: 1}).then(response => {
            setTimeout(() => {
             loading.close();
            }, 100)

            if (response.code == 200) {
              this.authdata=[];
              var auth = response.response;
              auth.forEach(item => {
                const menu = {
                  title: item.title,
                  name: item.name,
                  sons: item.sons,
                  id: item.id,
                  is_menu: item.is_menu,
                  pid: item.pid,
                  path: item.path,
                  sort: item.sort,
                  icon: item.icon,
                  component:item.component,
                  remark:item.remark
                }
                this.authdata.push(menu)
              })
            }
        }).catch(err => {
          setTimeout(() => {
             loading.close();
          }, 100)
        })
    },
    //保存权限
    rulesave(){
        this.$refs['form'].validate((valid) => {
            if (valid) {
                    authedit(this.data).then((res) => {
                    var code = res.code;
                    var msg = res.msg;
                    if (code == 200) {
                        this.$message.success(msg);
                        this.createFormBox=false
                        this.getAuth2()
                    } else {
                        this.$message.error(msg);
                    }
                })
            }
        })
    },
    //保存权限2
    rulesave2(){
        this.$refs['form2'].validate((valid) => {
            if (valid) {
                authaddnew(this.data2).then((res) => {
                    var code = res.code;
                    var msg = res.msg;
                    if (code == 200) {
                        this.$message.success(msg);
                        this.createFormBox2=false
                        this.getAuth2()
                    } else {
                        this.$message.error(msg);
                    }
                })
            }
        })
    },


  }
}
</script>
